package cn.kwq.pcsystem.utils;

import cn.kwq.pcsystem.dto.WyuDTO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/01/05/21:26
 * @Description:
 */
public class WyuUtils {
    @Value("${WYU.WYU_URL}")
    private String WYU_URL;
    @Value("${WYU.REFERER}")
    private String REFERER;


    public static WyuUtils getInstance(){
        return new WyuUtils();
    }

    /**
     * WYU系统登录获取信息
     *
     * @param token
     * @return 解析后数据
     */
    public WyuDTO getMessageByWyuSys(String token) throws IOException, ParseException {

        //得到html页面
        Document doc = Jsoup.connect(WYU_URL)
                .header("Cookie",token)
                .header("Referer",REFERER)
                .post();

        //解析出数据
        return doFilterMsg(doc);


    }

    /**
     * 解析需要的数据
     * @param doc doc对象（html）
     * @return 返回解析后数据
     */
    private WyuDTO doFilterMsg(Document doc) throws ParseException {

        Element div = doc.getElementsByClass("easyui-panel").first();
        Element table = div.getElementsByTag("table").first();
        Elements trs = table.getElementsByTag("tr");

        Element tr1 = trs.select("tr").get(0);
        Element tr2 = trs.select("tr").get(1);
        Element tr3 = trs.select("tr").get(2);

        String stuNum = tr1.select("label").get(0).text();
        String name = tr1.select("label").get(1).text();
        String year = tr1.select("label").get(2).text();

        String institute = tr2.select("label").get(0).text();
        String major = tr2.select("label").get(1).text();


        String wyuClass = tr3.select("label").get(0).text();
        String grade = tr3.select("label").get(1).text();


        Date enterYear= String2Date(year);

        return new WyuDTO(stuNum,name,institute,major,wyuClass,grade,enterYear);
    }

    /**
     * 字符串转年
     * @param year
     * @return 返回date对象
     * @throws ParseException
     */
    private Date String2Date(String year) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        Date date = formatter.parse(year);
        return date;
    }
}
